package org.dizem.intellipainter.component.color;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * User: dizem@126.com
 * Time: 12-2-18 下午3:19
 */
public class ColorLabel extends JLabel {
	private Color color;
	private static final int WIDTH = 20;
	private static final Dimension SIZE = new Dimension(WIDTH, WIDTH);
	private boolean mouseEntered;


	public ColorLabel(Color color, final ColorPickCallback callback) {
		setDoubleBuffered(true);
		this.color = color;
		addMouseListener(new MouseListener() {
			public void mouseClicked(MouseEvent e) {
				if (isEnabled()) {
					callback.onSelectColor(ColorLabel.this.color);
				}
			}

			public void mousePressed(MouseEvent e) {
			}

			public void mouseReleased(MouseEvent e) {
			}

			public void mouseEntered(MouseEvent e) {
				if (isEnabled()) {
					mouseEntered = true;
					repaint();
				}
			}

			public void mouseExited(MouseEvent e) {
				if (isEnabled()) {
					mouseEntered = false;
					repaint();
				}
			}
		});
	}

	public ColorLabel(int rgb, ColorPickCallback callback) {
		this(new Color(rgb), callback);
	}

	@Override
	public Dimension getPreferredSize() {
		return SIZE;
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		g.setColor(mouseEntered ? Color.ORANGE : Color.GRAY);
		g.drawRect(0, 0, WIDTH - 1, WIDTH - 1);
		if (mouseEntered) {
			g.drawRect(1, 1, WIDTH - 3, WIDTH - 3);
		}
		g.setColor(color);
		g.fillRect(2, 2, WIDTH - 4, WIDTH - 4);
	}


	public void setColor(Color color) {
		this.color = color;
		repaint();
	}
}
